import { Component, OnInit } from '@angular/core';
import { FadeInTop } from "../../shared/animations/fade-in-top.decorator";
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import {config} from '../../shared/smartadmin.config';
import { NotificationService } from "../../shared/utils/notification.service";

declare var $: any;
@FadeInTop()
@Component({
	selector: 'sa-param-file-page',
	templateUrl: './param-file-page.component.html',
})
export class ParamFilePageComponent implements OnInit {
	validatorOptions = {
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumber: {
				validators: {
					notEmpty: {
						message: '请输入车牌号码'
					}
				}
			},
			version: {
				validators: {
					notEmpty: {
						message: '请输入版本号'
					}
				}
			},
			fileToUpload: {
				validators: {
					notEmpty: {
						message: '请上传文件'
					}
				}
			}
		}

	}
	page: any = {
		carNumber: '',
		deviceId: '',
		version: '',
	};
	fileToUpload: File = null;
	pageType: string = 'new';
//	fileId = null;
	submitted = false;
	carList = [];
	fileUp = '';
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService,private notificationService: NotificationService) {
		activatedRoute.queryParams.subscribe(queryParams => {
//			this.fileId = queryParams.id;
			this.pageType = queryParams.type;
		});
	}
	//清除input文件缓存
	clearFile(){
		this.fileUp = '';
	}
	//文件上传change回调
	fileChange(files: FileList) {
		this.fileToUpload = files.item(0);
		if(!this.fileToUpload){
			this.message('请选择文件')
			return false;
		}
    }
	onSubmit(){
		if(!this.page.carNumber){
			this.message('请输入车牌号码')
			return;
		}
		this.submitted = true;
		$('#fileForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#fileForm').data('bootstrapValidator').isValid(); //验证是否通过
		if(isValid) {
			this.updata();
		}
	}
	//上传提交
	updata(){
		if(!this.fileToUpload){
     		this.message('没有文件,不允许执行');
        	return false;
        }
		let postParam = new FormData();
        postParam.append('carNumber', this.page.carNumber);
        postParam.append('deviceId', this.page.deviceId);
        postParam.append('version', this.page.version);
        postParam.append('file', this.fileToUpload);
       
        this.jsonApiService.form_http("experiment/upload.html", postParam).subscribe(data => {
        	if(data.success){
        		this.message(data.message);
        		this.router.navigate(['/data-management/param-file']);
        	}else{
        		this.message(data.message);
        	}
		})
    }
	message(data){
		this.notificationService.smallBox({
	      content: data,
	      timeout: 3000
	    });
	}
	//	返回资源列表页
	goBack(){
		this.router.navigate(['/data-management/param-file']);
	}
	ngOnInit(){
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				var that = this;
				$("#carNumberSelect2").select2({
		            language : "zh-CN",
		            minimumInputLength: 2,
	    			allowClear: true,
	    			placeholder:"请选择",
	    			ajax: {
			    		url: config.BaseURL+"stats/carListByCarNumber.html",
			    		dataType: 'json',
			    		delay: 50,
			    		method: "POST",
			    		xhrFields: {withCredentials: true},
			    		data: function (params){
			    		    return {"carNumber" :  params.term};
			    		},
			    		processResults: function(data, params) {
							var options = new Array();
							// 小于10个数量才判断重复
							if(data.data.length<=10){
								let arr = []
								let sameCar = []
								// 判断相同的车牌号
								for (let index = 0; index < data.data.length; index++) {
									let car = data.data[index];
									if(arr.indexOf(car.carNumber)!=-1){
										sameCar.push(car.carNumber)
									}else{
										arr.push(car.carNumber);
									}
								}
								$(data.data).each(function(index, car) {
									if(sameCar.indexOf(car.carNumber)!=-1){
										options.push({
											id: car.deviceId,
											text: car.carNumber+"["+car.parentName+"]"
										})
									}else{
										options.push({
											id: car.deviceId,
											text: car.carNumber
										})
									}
								});
							}else{
								$(data.data).each(function(index, car) {
									options.push({
										id: car.deviceId,
										text: car.carNumber
									})
								});
							}
							return {
								results: options //获取查询后的结果
							};
						},
			    		cache: true
			        },
		            templateResult : function (state){
		            	if (!state.id) {return state.text;}
		                var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		                return $state;
		            },
		       	}).on ("select2:select", function (e){
		        	var data = e.params.data;
					that.page.deviceId = data.id;
					if(data.text.indexOf('[') > 0){
						that.page.carNumber = data.text.split('[')[0];
					} else {
						that.page.carNumber = data.text;
					}
		        	// that.page.carNumber = data.text;
		        });
	    	})
		})
	}

}